<template>
  <div class="user-profile-page">
    <el-card>
      <template #header>
        <h2 class="title" @click="$router.push('/')">首页</h2>
        <span>个人中心</span>
      </template>

      <el-tabs v-model="activeTab">
        <!-- 个人资料 -->
        <el-tab-pane label="基本资料" name="profile">
          <el-form :model="userInfo" label-width="100px" :rules="rules" ref="profileForm">
            <el-form-item label="用户名" prop="name">
              <el-input v-model="userInfo.name"/>
            </el-form-item>

            <el-form-item label="学号" prop="studentId">
              <el-input v-model="userInfo.studentId" disabled/>
            </el-form-item>

            <el-form-item label="学分" prop="scores">
              <el-input v-model="userInfo.scores" disabled/>
            </el-form-item>

            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="userInfo.gender">
                <el-radio :label="1">男</el-radio>
                <el-radio :label="2">女</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="手机号" prop="phone">
              <el-input v-model="userInfo.phone"/>
            </el-form-item>

            <el-form-item label="QQ" prop="qq">
              <el-input v-model="userInfo.qq"/>
            </el-form-item>

            <el-form-item label="头像">
              <el-upload
                  class="avatar-uploader"
                  action="/api/file/upload"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
              >
                <img v-if="userInfo.avatar" :src="userInfo.avatar" class="avatar"/>
                <el-icon v-else class="avatar-uploader-icon">
                  <Plus/>
                </el-icon>
              </el-upload>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="updateProfile">保存修改</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 修改密码 -->
        <el-tab-pane label="修改密码" name="password">
          <el-form :model="passwordForm" label-width="100px" :rules="passwordRules" ref="passwordFormRef">
            <el-form-item label="原密码" prop="oldPassword">
              <el-input v-model="passwordForm.oldPassword" type="password" show-password/>
            </el-form-item>

            <el-form-item label="新密码" prop="newPassword">
              <el-input v-model="passwordForm.newPassword" type="password" show-password/>
            </el-form-item>

            <el-form-item label="确认新密码" prop="confirmPassword">
              <el-input v-model="passwordForm.confirmPassword" type="password" show-password/>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="updatePassword">修改密码</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 我的报名 -->
        <el-tab-pane label="我的报名" name="registrations">
          <el-button type="primary" @click="goToRegistrations">查看所有报名</el-button>

          <el-table :data="registeredActivities" style="width: 100%; margin-top: 20px">
            <el-table-column prop="activityName" label="活动名称"/>
            <el-table-column label="活动时间">
              <template #default="scope">
                {{ formatDate(scope.row.startTime) }}
              </template>
            </el-table-column>
            <el-table-column label="状态">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status)">
                  {{ getStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="签到状态">
              <template #default="scope">
                <el-tag v-if="scope.row.checkInTime" type="success">已签到</el-tag>
                <el-tag v-else-if="scope.row.status === 1" type="warning">未签到</el-tag>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #default="scope">
                <el-button
                    v-if="scope.row.status === 1 && !scope.row.checkInTime "
                    type="success"
                    size="small"
                    @click="handleCheckIn(scope.row.id)"
                >
                  签到
                </el-button>
                <el-button
                    type="primary"
                    size="small"
                    @click="viewActivity(scope.row.activityId)"
                >
                  查看活动
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted} from 'vue'
import {useUserStore} from '@/stores/user'
import {ElMessage, ElMessageBox} from 'element-plus'
import {getUserInfo, updateUserInfo, updatePassword as updatePasswordAPI} from '@/api/user'
import {getUserRegistrationList, checkInRegistration} from '@/api/registration'
import {useRouter} from 'vue-router'
import {Plus} from '@element-plus/icons-vue'

const router = useRouter()
const userStore = useUserStore()
const activeTab = ref('profile')
const profileForm = ref(null)
const passwordFormRef = ref(null)

// 用户基本信息
const userInfo = ref({
  id: null,
  name: '',
  studentId: '',
  avatar: '',
  gender: null,
  phone: '',
  qq: '',
})

// 密码表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: '',
})

// 报名记录
const registeredActivities = ref([])

// 表单校验规则
const rules = {
  name: [{required: true, message: '请输入用户名', trigger: 'blur'}],
  phone: [
    {required: true, message: '请输入手机号', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur'}
  ],
  qq: [{required: true, message: '请输入QQ号', trigger: 'blur'}],
  gender: [{required: true, message: '请选择性别', trigger: 'change'}]
}

// 密码校验规则
const passwordRules = {
  oldPassword: [{required: true, message: '请输入原密码', trigger: 'blur'}],
  newPassword: [
    {required: true, message: '请输入新密码', trigger: 'blur'},
    {min: 6, message: '密码不能少于6位', trigger: 'blur'}
  ],
  confirmPassword: [
    {required: true, message: '请再次输入新密码', trigger: 'blur'},
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 更新个人资料
const updateProfile = async () => {
  try {
    await profileForm.value.validate()

    const res = await updateUserInfo(userInfo.value)
    if (res.code === 200) {
      ElMessage.success('个人信息更新成功')
      // 更新store中的用户信息
      userStore.setUserInfo(res.data)
    } else {
      ElMessage.error(res.msg || '更新失败')
    }
  } catch (error) {
    console.error('表单验证失败', error)
  }
}

// 修改密码
const updatePassword = async () => {
  try {
    await passwordFormRef.value.validate()

    const res = await updatePasswordAPI({
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword
    })

    if (res.code === 200) {
      ElMessage.success('密码修改成功')
      // 清空表单
      passwordForm.oldPassword = ''
      passwordForm.newPassword = ''
      passwordForm.confirmPassword = ''
    } else {
      ElMessage.error(res.msg || '密码修改失败')
    }
  } catch (error) {
    console.error('表单验证失败', error)
  }
}

// 头像上传成功
const handleAvatarSuccess = (response) => {
  if (response.code === 200) {
    userInfo.value.avatar = response.data
  }
}

// 获取用户信息
const fetchUserInfo = async () => {
  const res = await getUserInfo()
  if (res.code === 200) {
    userInfo.value = res.data
  }
}

// 获取用户报名记录
const fetchUserRegistrations = async () => {
  try {
    const res = await getUserRegistrationList({
      page: 1,
      size: 5,
      status: null
    })
    if (res.code === 200) {
      registeredActivities.value = res.data.records || []
    }
  } catch (error) {
    console.error('获取报名记录失败:', error)
  }
}

// 签到
const handleCheckIn = async (registrationId) => {
  try {
    ElMessageBox.confirm('确认签到当前活动?', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async () => {
      const res = await checkInRegistration(registrationId)
      if (res.code === 200) {
        ElMessage.success('签到成功')
        fetchUserRegistrations()
      } else {
        ElMessage.error(res.msg || '签到失败')
      }
    })
  } catch (error) {
    console.error('签到失败:', error)
  }
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleString()
}

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 0:
      return '待审核'
    case 1:
      return '已通过'
    case 2:
      return '已拒绝'
    case 3:
      return '已取消'
    default:
      return '未知状态'
  }
}

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case 0:
      return 'info'
    case 1:
      return 'success'
    case 2:
      return 'danger'
    case 3:
      return 'warning'
    default:
      return 'info'
  }
}

// 判断是否可以签到
const canCheckIn = (registration) => {
  if (!registration.activityStartTime || !registration.activityEndTime) return false

  const now = new Date()
  const startTime = new Date(registration.activityStartTime)
  const endTime = new Date(registration.activityEndTime)

  return now >= startTime && now <= endTime
}

// 查看活动详情
const viewActivity = (activityId) => {
  router.push(`/activity/${activityId}`)
}

// 查看所有报名
const goToRegistrations = () => {
  router.push('/registrations')
}

onMounted(async () => {
  await fetchUserInfo()
  await fetchUserRegistrations()
})
</script>

<style scoped>
.user-profile-page {
  padding: 20px;
}

.title {
  cursor: pointer;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.avatar-uploader {
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  border: 1px dashed #ccc;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
